package org.jeecg.modules.demo.checkOrder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.checkOrder.entity.CheckOrderRk;
import org.jeecg.modules.demo.checkOrder.entity.checkOrder;
import org.jeecg.modules.demo.checkOrder.service.ICheckOrderRkService;
import org.jeecg.modules.demo.checkOrder.service.IcheckOrderService;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.soOrderDetail.entity.SoOrderDetail;
import org.jeecg.modules.demo.utils.ReflectUtil;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jeecg.modules.demo.warehouseorder.entity.WarehouseOrder;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: checkOrder
 * @Author: jeecg-boot
 * @Date:   2022-01-19
 * @Version: V1.0
 */
@Api(tags="checkOrder")
@RestController
@RequestMapping("/checkOrder/checkOrder")
@Slf4j
public class checkOrderController extends JeecgController<checkOrder, IcheckOrderService> {

	@Autowired
	private IcheckOrderService checkOrderService;

	@Autowired
	private ICheckOrderRkService checkOrderRkService;
	@Autowired
	private IPuBuyOrderService puBuyOrderService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param checkOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "盘点单-分页列表查询")
	@ApiOperation(value="盘点单-分页列表查询", notes="盘点单-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="yunxiao/checkOrder/checkOrderList")
	public Result<?> queryPageList(checkOrder checkOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		try{
			QueryWrapper<checkOrder> queryWrapper = QueryGenerator.initQueryWrapper(checkOrder, req.getParameterMap());
			queryWrapper.eq("SHANCHU",0);
			if(ReflectUtil.isObjectNull(checkOrder)){
				queryWrapper.eq("SHENHE",0);
			}
			Page<checkOrder> page = new Page<checkOrder>(pageNo, pageSize);
			IPage<checkOrder> pageList = checkOrderService.page(page, queryWrapper);
			return Result.OK(pageList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}

	/**
     *   添加
     * @param checkOrder
     * @return
     */
    @AutoLog(value = "盘点单-添加")
    @ApiOperation(value="盘点单-添加", notes="盘点单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody checkOrder checkOrder,HttpServletRequest req) {
		try{
			String str = checkOrderService.getMaxCode();
			Map<String,String> map = new HashMap<>();
			if(str==null){
				map.put("maxCode",null);
			}else{
				map.put("maxCode",str);
			}
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			String name = precode+"PD_";
			String resultCode = generateOddUtil.createCode(map,name);
			checkOrder.setPdNo(resultCode);
			checkOrder.setShenhe(0);
			checkOrder.setShanchu(0);
			checkOrder.setCreateTime(new Date());
			List<CheckOrderRk> orderRks = checkOrderRkService.getByWhNum(checkOrder.getWhNum());
			if(orderRks.isEmpty()){
				return Result.error("该仓库暂未使用，提取失败！");
			}
			for (CheckOrderRk checkOrderRk : orderRks) {
				checkOrderRk.setPoStaff(checkOrder.getPoStaff());
				checkOrderRk.setDepartment(checkOrder.getDepartment());
				checkOrderRk.setCreateTime(new Date());
				checkOrderRk.setShenhe(0);
				checkOrderRk.setShanchu(0);
				checkOrderRk.setPdNo(resultCode);
			}
			if(checkOrderService.addCheckOrderAndRk(checkOrder,orderRks)){
				return Result.OK("提取成功！");
			}
			return Result.error(300,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
    }
	 /**
	  *  审核盘点单
	  * @param checkOrder
	  * @return
	  */
	 @AutoLog(value = "盘点单-审核")
	 @ApiOperation(value="盘点单-审核", notes="盘点单-审核")
	 @PostMapping(value = "/checkOrderList")
	 public Result<?> checkOrderList(@RequestBody checkOrder checkOrder,HttpServletRequest req) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(checkOrder.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if(checkOrder.getShenhe()==1){
				 return Result.error(300,"已审核，无需重复审核！");
			 }

			 List<CheckOrderRk> checkOrderRks = checkOrderRkService.getByShenHe(checkOrder.getPdNo());
		 	if(!checkOrderRks.isEmpty()){
		 		return Result.error(300,"数据未盘点完毕！");
			}
			 String tenantId = req.getHeader("tenant-id");
			 String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			 List<CheckOrderRk> orderRks = checkOrderRkService.getByPdNo(checkOrder.getPdNo());
		 	if(checkOrderService.check(checkOrder,orderRks,precode)){
				return Result.OK("审核成功!");
			}
			 return Result.error(300,"网络故障！");
		 }catch (Exception e){
		 	e.printStackTrace();
		 	return Result.error(300,"网络故障！");
		 }
	 }
	 /**
	  *  弃审
	  * @param checkOrder
	  * @return
	  */
	 @AutoLog(value = "盘点单-弃审")
	 @ApiOperation(value="盘点单-弃审", notes="盘点单-弃审")
	 @PostMapping(value = "/unCheckOrderList")
	 public Result<?> unCheckOrderList(@RequestBody checkOrder checkOrder) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(checkOrder.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			if(checkOrder.getShenhe()==0){
				return Result.error(300,"请先审核单据！");
			}

			List<WarehouseOrder> warehouseOrders = checkOrderService.getWareHouseOrderByPdNo(checkOrder.getPdNo());
			List<SoOrderDetail> soOrderDetails = checkOrderService.getSoOrderDetailsByPdNo(checkOrder.getPdNo());
			if(!warehouseOrders.isEmpty()||!soOrderDetails.isEmpty()){
				return Result.error(300,"后续单据已审核，无法弃审！");
			}
			if(checkOrderService.unCheck(checkOrder)){
				return Result.OK("弃审成功!");
			}
			 return Result.error(300,"网络故障！");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(300,"网络故障！");
		 }
	 }
    /**
     *  编辑
     * @param checkOrder
     * @return
     */
    @AutoLog(value = "盘点单-编辑")
    @ApiOperation(value="盘点单-编辑", notes="盘点单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody checkOrder checkOrder) {
        checkOrderService.updateById(checkOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "盘点单-通过id删除")
    @ApiOperation(value="盘点单-通过id删除", notes="盘点单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        try{
        	checkOrder checkOrder = checkOrderService.getById(id);
        	if(checkOrder.getShenhe()==1){
        		return Result.error(300,"单据已审核，无法删除！");
			}
            if(checkOrderService.deleteOrder(checkOrder)){
				return Result.OK("删除成功!");
			}
			return Result.error(300,"网络故障！");
		}catch (Exception e){
        	e.printStackTrace();
        	return Result.error(300,"网络故障！");
		}
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "盘点单-批量删除")
    @ApiOperation(value="盘点单-批量删除", notes="盘点单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.checkOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, checkOrder checkOrder) {
        return super.exportXls(request, checkOrder, checkOrder.class, "checkOrder");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, checkOrder.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-CheckOrderRk-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "盘点项-通过主表ID查询")
	@ApiOperation(value="盘点项-通过主表ID查询", notes="盘点项-通过主表ID查询")
	@GetMapping(value = "/listCheckOrderRkByMainId")
    public Result<?> listCheckOrderRkByMainId(CheckOrderRk checkOrderRk,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<CheckOrderRk> queryWrapper = QueryGenerator.initQueryWrapper(checkOrderRk, req.getParameterMap());
        Page<CheckOrderRk> page = new Page<CheckOrderRk>(pageNo, pageSize);
        IPage<CheckOrderRk> pageList = checkOrderRkService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param checkOrderRk
	 * @return
	 */
	@AutoLog(value = "盘点项-添加")
	@ApiOperation(value="盘点项-添加", notes="盘点项-添加")
	@PostMapping(value = "/addCheckOrderRk")
	public Result<?> addCheckOrderRk(@RequestBody CheckOrderRk checkOrderRk) {
		try{
			checkOrder checkOrder = checkOrderService.getByPdNo(checkOrderRk.getPdNo());
			checkOrderRk.setWhNum(checkOrder.getWhNum());
			checkOrderRk.setShenhe(0);
			checkOrderRk.setShanchu(0);
			checkOrderRk.setSaleman(checkOrder.getSaleman());
			checkOrderRkService.save(checkOrderRk);
			return Result.OK("添加成功！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}

    /**
	 * 编辑
	 * @param checkOrderRk
	 * @return
	 */
	@AutoLog(value = "盘点项-编辑")
	@ApiOperation(value="盘点项-编辑", notes="盘点项-编辑")
	@PostMapping(value = "/editCheckOrderRk")
	public Result<?> editCheckOrderRk(@RequestBody CheckOrderRk checkOrderRk) {
		try{
			checkOrderRkService.updateById(checkOrderRk);
			return Result.OK("编辑成功!");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "盘点项-通过id删除")
	@ApiOperation(value="盘点项-通过id删除", notes="盘点项-通过id删除")
	@DeleteMapping(value = "/deleteCheckOrderRk")
	public Result<?> deleteCheckOrderRk(@RequestParam(name="id",required=true) String id) {
		checkOrderRkService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "盘点项-批量删除")
	@ApiOperation(value="盘点项-批量删除", notes="盘点项-批量删除")
	@DeleteMapping(value = "/deleteBatchCheckOrderRk")
	public Result<?> deleteBatchCheckOrderRk(@RequestParam(name="ids",required=true) String ids) {
	    this.checkOrderRkService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportCheckOrderRk")
    public ModelAndView exportCheckOrderRk(HttpServletRequest request, CheckOrderRk checkOrderRk) {
		 // Step.1 组装查询条件
		 QueryWrapper<CheckOrderRk> queryWrapper = QueryGenerator.initQueryWrapper(checkOrderRk, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<CheckOrderRk> pageList = checkOrderRkService.list(queryWrapper);
		 List<CheckOrderRk> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "CheckOrderRk"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, CheckOrderRk.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("CheckOrderRk报表", "导出人:" + sysUser.getRealname(), "CheckOrderRk"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importCheckOrderRk/{mainId}")
    public Result<?> importCheckOrderRk(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<CheckOrderRk> list = ExcelImportUtil.importExcel(file.getInputStream(), CheckOrderRk.class, params);
				 for (CheckOrderRk temp : list) {
                    temp.setPdNo(mainId);
				 }
				 long start = System.currentTimeMillis();
				 checkOrderRkService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-CheckOrderRk-end----------------------------------------------*/




}
